package com.peng.immodule.im;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Process;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.Log;

import com.peng.immodule.analytics.EMTimeTag;
import com.peng.immodule.util.CryptoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

/**
 * Created by M_genius on 2018/3/6 15:25.
 * 描述：
 */

public class IMClient {

    public static final String TAG = "EMClient";
    private static IMClient instance = null;
    static boolean libraryLoaded = false;
    private EMGroupManager groupManager;
    private EMChatRoomManager chatroomManager;
    private EMChatManager chatManager;
    private EMContactManager contactManager;
    private EMCallManager callManager;
    private EMPushManager pushManager;
    private EMAChatClient emaObject;

    private Context mContext;
    private ExecutorService executor = null;
    private ExecutorService mainQueue = Executors.newSingleThreadExecutor();
    private ExecutorService sendQueue = Executors.newSingleThreadExecutor();

    private EMEncryptProvider encryptProvider = null;
    private CryptoUtils cryptoUtils = new CryptoUtils();
    private boolean sdkInited = false;
    private b mChatConfigPrivate;
    private List<EMConnectionListener> connectionListeners = Collections.synchronizedList(new ArrayList());
    private EMClient.MyConnectionListener connectionListener = new EMClient.MyConnectionListener();
    private EMSmartHeartBeat smartHeartbeat = null;
    private List<EMClientListener> clientListeners = Collections.synchronizedList(new ArrayList());
    private List<EMMultiDeviceListener> multiDeviceListeners = Collections.synchronizedList(new ArrayList());
    private EMClient.MyMultiDeviceListener multiDeviceListenerImpl = new EMClient.MyMultiDeviceListener();
    private WakeLock wakeLock;
    public static final String VERSION = "3.3.3";
    private static final int JOB_ID = 11;
    private static final int JOB_INTERVAL = 60000;
    boolean stopService;

    private BroadcastReceiver connectivityBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context var1, Intent var2) {
            String var3 = var2.getAction();
            if(!var3.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                EMLog.d("EMClient", "skip no connectivity action");
            } else {
                EMLog.d("EMClient", "connectivity receiver onReceiver");
                EMClient.this.execute(new Runnable() {
                    public void run() {
                        EMClient.this.onNetworkChanged();
                    }
                });
            }
        }
    };
    private IMClient.AppStateListener appStateListener;
    private int activitySize = 0;

    private IMClient() {
    }

    public static IMClient getInstance() {
        if(instance == null) {
            loadLibrary();
            instance = new IMClient();
        }

        return instance;
    }

    public void init(Context var1, EMOptions var2) {
        if(!this.sdkInited) {
            EMTimeTag var3 = new EMTimeTag();
            var3.start();
            this.mContext = var1.getApplicationContext();
            this.registerActivityLifecycleCallbacks();
            this.mChatConfigPrivate = new b();
            this.mChatConfigPrivate.a(var1, var2);
            var2.setConfig(this.mChatConfigPrivate);
            DeviceUuidFactory var4 = new DeviceUuidFactory(getInstance().getContext());
            this.getChatConfigPrivate().g(var4.getDeviceUuid().toString());
            this.getChatConfigPrivate().h(Build.MANUFACTURER + Build.MODEL);
            this.emaObject = EMAChatClient.create(this.mChatConfigPrivate.a);
            this.emaObject.addConnectionListener(this.connectionListener);
            this.emaObject.addMultiDeviceListener(this.multiDeviceListenerImpl);
            this.executor = Executors.newCachedThreadPool();
            this.cryptoUtils.init(1);
            this.initManagers();
            final String var5 = EMSessionManager.getInstance().getLastLoginUser();
            EMLog.e("EMClient", "is autoLogin : " + var2.getAutoLogin());
            EMLog.e("EMClient", "lastLoginUser : " + var5);
            EMLog.e("EMClient", "hyphenate SDK is initialized with version : " + this.getChatConfigPrivate().e());
            PowerManager var6 = (PowerManager)this.mContext.getSystemService("power");
            this.wakeLock = var6.newWakeLock(1, "emclient");
            this.sdkInited = true;
            if(var2.getAutoLogin() && !EMSessionManager.getInstance().isLastLoginWithToken() && this.isLoggedInBefore()) {
                final String var7 = EMSessionManager.getInstance().getLastLoginPwd();
                EMSessionManager.getInstance().currentUser = new EMContact(var5);
                final EMCallBack var9 = new EMCallBack() {
                    public void onSuccess() {
                        Log.d("EMClient", "hyphenate login onSuccess");
                        EMSessionManager.getInstance().currentUser = new EMContact(var5);
                    }

                    public void onError(int var1, String var2) {
                        Log.d("EMClient", "hyphenate login onError");
                    }

                    public void onProgress(int var1, String var2) {
                    }
                };
                this.execute(new Runnable() {
                    public void run() {
                        EMClient.this.getChatConfigPrivate().b(var5);
                        EMClient.this.groupManager().loadAllGroups();
                        EMClient.this.chatManager().loadAllConversationsFromDB();
                        EMClient.this.autoLogin(var5, var7, var9);
                    }
                });
            }

            var3.stop();
            EMLog.e("EMClient", "[Collector][sdk init]init time is : " + var3.timeStr());
        }
    }

    public void createAccount(String var1, String var2) throws HyphenateException {
        var1 = var1.toLowerCase();
        Pattern var3 = Pattern.compile("^[a-zA-Z0-9_-]+$");
        boolean var4 = var3.matcher(var1).find();
        if(!var4) {
            throw new HyphenateException(205, "illegal user name");
        } else {
            EMAError var5 = this.emaObject.createAccount(var1, var2);
            this.handleError(var5);
        }
    }

    public void login(String var1, String var2, EMCallBack var3) throws IllegalArgumentException {
        if(var3 == null) {
            throw new IllegalArgumentException("callback is null!");
        } else if(var1 != null && var2 != null && !var1.equals("") && !var2.equals("")) {
            if(TextUtils.isEmpty(this.getChatConfigPrivate().l())) {
                throw new IllegalArgumentException("please setup your appkey either in AndroidManifest.xml or through the EMOptions");
            } else if(!this.sdkInited) {
                var3.onError(1, "sdk not initialized");
            } else {
                var1 = var1.toLowerCase();
                this._login(var1, var2, var3, false, false);
            }
        } else {
            throw new IllegalArgumentException("username or password is null or empty!");
        }
    }

    public void loginWithToken(String var1, String var2, EMCallBack var3) {
        if(TextUtils.isEmpty(this.getChatConfigPrivate().l())) {
            throw new RuntimeException("please setup your appkey either in AndroidManifest.xml or through the EMOptions");
        } else if(var3 == null) {
            throw new IllegalArgumentException("callback is null!");
        } else if(var1 != null && var2 != null && !var1.equals("") && !var2.equals("")) {
            if(!this.sdkInited) {
                var3.onError(1, "sdk not initialized");
            } else {
                var1 = var1.toLowerCase();
                this._login(var1, var2, var3, false, true);
            }
        } else {
            throw new IllegalArgumentException("username or password is null or empty!");
        }
    }

    public int logout(boolean var1) {
        try {
            EMPushHelper.getInstance().onDestroy(var1);
        } catch (HyphenateException var3) {
            var3.printStackTrace();
            return 212;
        }

        this.logout();
        return 0;
    }

    void logout() {
        EMLog.d("EMClient", " SDK Logout");

        try {
            if(this.connectivityBroadcastReceiver != null) {
                this.mContext.unregisterReceiver(this.connectivityBroadcastReceiver);
            }
        } catch (Exception var3) {
            ;
        }

        EMSessionManager.getInstance().clearLastLoginUser();
        EMSessionManager.getInstance().clearLastLoginPwd();
        if(this.smartHeartbeat != null) {
            this.smartHeartbeat.stop();
        }

        if(this.wakeLock.isHeld()) {
            this.wakeLock.release();
        }

        if(this.emaObject != null) {
            this.emaObject.logout();
        }

        if(this.chatManager != null) {
            this.chatManager.onLogout();
        }

        if(this.groupManager != null) {
            this.groupManager.onLogout();
        }

        if(this.contactManager != null) {
            this.contactManager.onLogout();
        }

        if(this.chatroomManager != null) {
            this.chatroomManager.onLogout();
        }

        try {
            a.a().f();
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        if(b.a()) {
            com.hyphenate.a.a.c();
        }

        if(this.mContext != null) {
            EMMonitor.getInstance().getMonitorDB().b(this.mContext.getPackageName());
        }

        this.cancelJob();
        this.doStopService();
    }

    public void logout(final boolean var1, final EMCallBack var2) {
        (new Thread() {
            public void run() {
                int var1x = EMClient.this.logout(var1);
                if(var1x != 0) {
                    if(var2 != null) {
                        var2.onError(var1x, "faild to unbind device token");
                    }
                } else if(var2 != null) {
                    var2.onSuccess();
                }

            }
        }).start();
    }

    void logout(final EMCallBack var1) {
        Thread var2 = new Thread() {
            public void run() {
                if(var1 != null) {
                    var1.onProgress(0, (String)null);
                }

                EMClient.this.logout();
                if(var1 != null) {
                    var1.onSuccess();
                }

            }
        };
        var2.setPriority(9);
        var2.start();
    }

    public void changeAppkey(String var1) throws HyphenateException {
        EMAError var2 = this.emaObject.changeAppkey(var1);
        if(var2.errCode() == 0) {
            this.getOptions().updatePath(var1);
        }

        this.handleError(var2);
    }

    public void addConnectionListener(final EMConnectionListener var1) {
        if(var1 != null) {
            List var2 = this.connectionListeners;
            synchronized(this.connectionListeners) {
                if(!this.connectionListeners.contains(var1)) {
                    this.connectionListeners.add(var1);
                }
            }

            this.execute(new Runnable() {
                public void run() {
                    if(EMClient.this.isConnected()) {
                        var1.onConnected();
                    } else {
                        var1.onDisconnected(2);
                    }

                }
            });
        }
    }

    public void addClientListener(EMClientListener var1) {
        this.clientListeners.add(var1);
    }

    public void removeClientListener(EMClientListener var1) {
        this.clientListeners.remove(var1);
    }

    public void removeConnectionListener(EMConnectionListener var1) {
        if(var1 != null) {
            List var2 = this.connectionListeners;
            synchronized(this.connectionListeners) {
                this.connectionListeners.remove(var1);
            }
        }
    }

    public EMGroupManager groupManager() {
        if(this.groupManager == null) {
            this.groupManager = new EMGroupManager(this, this.emaObject.getGroupManager());
        }

        return this.groupManager;
    }

    public EMPushManager pushManager() {
        if(this.pushManager == null) {
            this.pushManager = new EMPushManager(this, this.emaObject.getPushMnager());
        }

        return this.pushManager;
    }

    public EMChatRoomManager chatroomManager() {
        if(this.chatroomManager == null) {
            this.chatroomManager = new EMChatRoomManager(this, this.emaObject.getChatRoomManager());
        }

        return this.chatroomManager;
    }

    public EMChatManager chatManager() {
        if(this.chatManager == null) {
            this.chatManager = new EMChatManager(this, this.emaObject.getChatManager());
        }

        return this.chatManager;
    }

    public EMContactManager contactManager() {
        if(this.contactManager == null) {
            this.contactManager = new EMContactManager(this, this.emaObject.getContactManager());
        }

        return this.contactManager;
    }

    public EMCallManager callManager() {
        if(this.callManager == null) {
            this.callManager = new EMCallManager(this, this.emaObject.getCallManager());
        }

        return this.callManager;
    }

    public Context getContext() {
        return this.mContext;
    }

    public String getCurrentUser() {
        return EMSessionManager.getInstance().currentUser != null && EMSessionManager.getInstance().currentUser.username != null && !EMSessionManager.getInstance().currentUser.username.equals("")?EMSessionManager.getInstance().currentUser.username:EMSessionManager.getInstance().getLastLoginUser();
    }

    public boolean isConnected() {
        return this.emaObject.isConnected();
    }

    public void setDebugMode(boolean var1) {
        if(this.sdkInited) {
            String var2 = a.a().e();
            if(var2 != null) {
                var1 = Boolean.parseBoolean(var2);
            }
        }

        EMLog.debugMode = var1;
        this.getChatConfigPrivate().c(var1);
    }

    @Deprecated
    public boolean updateCurrentUserNick(String var1) {
        return this.pushManager().updatePushNickname(var1);
    }

    public void uploadLog(EMCallBack var1) {
        this.chatManager().emaObject.uploadLog();
    }

    public List<EMContact> getRobotsFromServer() throws HyphenateException {
        return EMExtraService.getInstance().getRobotsFromServer();
    }

    public EMOptions getOptions() {
        return this.mChatConfigPrivate.b();
    }

    public String compressLogs() throws HyphenateException {
        EMAError var1 = new EMAError();
        String var2 = this.emaObject.compressLogs(var1);
        this.handleError(var1);
        return var2;
    }

    public void addMultiDeviceListener(EMMultiDeviceListener var1) {
        this.multiDeviceListeners.add(var1);
    }

    public void removeMultiDeviceListener(EMMultiDeviceListener var1) {
        this.multiDeviceListeners.remove(var1);
    }

    public List<EMDeviceInfo> getLoggedInDevicesFromServer(String var1, String var2) throws HyphenateException {
        EMAError var3 = new EMAError();
        List var4 = this.emaObject.getLoggedInDevicesFromServer(var1, var2, var3);
        this.handleError(var3);
        ArrayList var5 = new ArrayList();
        Iterator var6 = var4.iterator();

        while(var6.hasNext()) {
            EMADeviceInfo var7 = (EMADeviceInfo)var6.next();
            var5.add(new EMDeviceInfo(var7));
        }

        return var5;
    }

    public void kickDevice(String var1, String var2, String var3) throws HyphenateException {
        EMAError var4 = new EMAError();
        this.emaObject.kickDevice(var1, var2, var3, var4);
        this.handleError(var4);
    }

    public void kickAllDevices(String var1, String var2) throws HyphenateException {
        EMAError var3 = new EMAError();
        this.emaObject.kickAllDevices(var1, var2, var3);
        this.handleError(var3);
    }

    private void initManagers() {
        EMHttpClient.getInstance().onInit(this.mChatConfigPrivate);
        this.chatManager();
        this.contactManager();
        this.groupManager();
        this.chatroomManager();
        this.setNatvieNetworkCallback();
    }

    void autoLogin(String var1, String var2, EMCallBack var3) {
        this._login(var1, var2, var3, true, false);
    }

    void _login(final String var1, final String var2, final EMCallBack var3, final boolean var4, final boolean var5) {
        if(this.getChatConfigPrivate() != null && this.sdkInited) {
            EMLog.e("EMClient", "emchat manager login in process:" + Process.myPid());
            this.execute(new Runnable() {
                public void run() {
                    if(var1 == null) {
                        var3.onError(101, "Invalid user name");
                    } else {
                        EMAError var1x = new EMAError();
                        if(var4) {
                            EMClient.this.onNewLogin();
                            EMClient.this.emaObject.autoLogin(var1, var2, var1x);
                            if(var1x.errCode() == 0) {
                                EMClient.this.checkPushAvailable();
                                var3.onSuccess();
                            } else {
                                var3.onError(var1x.errCode(), var1x.errMsg());
                            }
                        } else {
                            if(!var5) {
                                EMClient.this.emaObject.login(var1, var2, var1x);
                            } else {
                                EMClient.this.emaObject.loginWithToken(var1, var2, var1x);
                            }

                            if(var1x.errCode() == 0) {
                                EMSessionManager.getInstance().setLastLoginUser(var1);
                                EMSessionManager.getInstance().setLastLoginPwd(var2);
                                EMSessionManager.getInstance().setLastLoginWithToken(var5);
                                EMClient.this.onNewLogin();
                                EMClient.this.checkPushAvailable();
                                var3.onSuccess();
                            } else {
                                EMClient.this.doStopService();
                                var3.onError(var1x.errCode(), var1x.errMsg());
                            }
                        }

                        if(var1x.errCode() == 0) {
                            EMClient.this.setPresence(EMClient.this.getLocationString(var4));
                        }

                        if(var1x.errCode() == 202) {
                            EMSessionManager.getInstance().clearLastLoginPwd();
                        }

                    }
                }
            });
        } else {
            var3.onError(1, "");
        }
    }

    void checkPushAvailable() {
        boolean var1 = EMPushHelper.getInstance().checkAvailablePushService();
        if(var1) {
            EMPushHelper.getInstance().sendDeviceTokenToServer();
        } else {
            this.sendEmptyToken();
        }

    }

    private void sendEmptyToken() {
        for(int var1 = 0; var1 < 3; ++var1) {
            boolean var2 = EMPushHelper.getInstance().sendTokenToServer("");
            if(var2) {
                return;
            }
        }

    }

    void onNewLogin() {
        EMLog.d("EMClient", "on new login created");
        String var1 = EMSessionManager.getInstance().getLastLoginUser();
        PathUtil.getInstance().initDirs(this.getChatConfigPrivate().l(), var1, this.mContext);
        c.a(var1, this.mChatConfigPrivate);
        c.a().a(new com.hyphenate.chat.a.c.a() {
            public void onMigrationFinish(final boolean var1) {
                EMClient.this.execute(new Runnable() {
                    public void run() {
                        if(EMClient.this.clientListeners != null) {
                            synchronized(EMClient.this.clientListeners) {
                                Iterator var2 = EMClient.this.clientListeners.iterator();

                                while(var2.hasNext()) {
                                    EMClientListener var3 = (EMClientListener)var2.next();
                                    var3.onMigrate2x(var1);
                                }
                            }
                        }

                    }
                });
            }
        });
        c.a().c();
        this.saveAppname();
        EMPushHelper.getInstance().onInit();
        a.a().a(this.mChatConfigPrivate);
        this.mContext.registerReceiver(this.connectivityBroadcastReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
        if(this.smartHeartbeat == null) {
            this.smartHeartbeat = EMSmartHeartBeat.create(this.mContext);
        }

        this.smartHeartbeat.onInit();
        if(this.getChatConfigPrivate().a.hasHeartBeatCustomizedParams()) {
            this.smartHeartbeat.setCustomizedParams(this.getChatConfigPrivate().a.getWifiHeartBeatCustomizedParams(), this.getChatConfigPrivate().a.getMobileHeartBeatCustomizedParams());
        }

        this.scheduleJob();
    }

    @TargetApi(21)
    void scheduleJob() {
        if(Utils.isSdk21()) {
            try {
                Intent var1 = new Intent(this.getContext(), EMJobService.class);
                this.mContext.startService(var1);
                JobInfo.Builder var2 = new JobInfo.Builder(11, new ComponentName(this.getContext(), EMJobService.class));
                var2.setPeriodic(60000L);
                var2.setRequiredNetworkType(1);
                var2.setPersisted(true);
                JobScheduler var3 = (JobScheduler)this.mContext.getSystemService("jobscheduler");
                var3.schedule(var2.build());
            } catch (Exception var4) {
                ;
            }
        }

    }

    @TargetApi(21)
    void cancelJob() {
        if(Utils.isSdk21()) {
            try {
                JobScheduler var1 = (JobScheduler)this.mContext.getSystemService("jobscheduler");
                var1.cancel(11);
                this.mContext.stopService(new Intent(this.mContext, EMJobService.class));
            } catch (Exception var2) {
                ;
            }
        }

    }

    public String getAccessToken() {
        return this.getChatConfigPrivate().n();
    }

    private static void loadLibrary() {
        if(!libraryLoaded) {
            try {
                System.loadLibrary("hyphenate_av");
            } catch (Throwable var2) {
                var2.printStackTrace();
            }

            try {
                System.loadLibrary("hyphenate_av_recorder");
            } catch (Throwable var1) {
                var1.printStackTrace();
            }

            System.loadLibrary("hyphenate");
            libraryLoaded = true;
        }

    }

    CryptoUtils getCryptoUtils() {
        return cryptoUtils;
    }

    void doStartService() {
        if(this.mContext != null) {
            EMLog.d("EMClient", "do start service: context:" + this.mContext);
            this.stopService = false;

            try {
                Intent var1 = new Intent(this.mContext, EMChatService.class);
                this.mContext.startService(var1);
            } catch (Exception var2) {
                EMLog.d("EMClient", "exception in start service, e: " + var2.getMessage());
            }

        }
    }

    void doStopService() {
        try {
            if(this.mContext == null) {
                EMLog.w("EMClient", "applicationContext is null, the server is not started before");
                return;
            }

            EMLog.d("EMClient", "do stop service");
            this.stopService = true;
            Intent var1 = new Intent(this.mContext, EMChatService.class);
            this.mContext.stopService(var1);
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    void saveAppname() {
        EMMonitor.getInstance().getMonitorDB().a(this.mContext.getPackageName());
    }

    void execute(Runnable var1) {
        this.executor.execute(var1);
    }

    void executeOnMainQueue(Runnable var1) {
        this.mainQueue.submit(var1);
    }

    void executeOnSendQueue(Runnable var1) {
        this.sendQueue.submit(var1);
    }

    b getChatConfigPrivate() {
        return this.mChatConfigPrivate;
    }

    void setNatvieNetworkCallback() {
        EMANetCallback var1 = new EMANetCallback() {
            public int getNetState() {
                return !NetUtils.hasDataConnection(EMClient.this.mContext)?EMANetwork.NETWORK_NONE.ordinal():(NetUtils.isWifiConnected(EMClient.this.mContext)?EMANetwork.NETWORK_WIFI.ordinal():(NetUtils.isMobileConnected(EMClient.this.mContext)?EMANetwork.NETWORK_MOBILE.ordinal():(NetUtils.isEthernetConnected(EMClient.this.mContext)?EMANetwork.NETWORK_CABLE.ordinal():EMANetwork.NETWORK_NONE.ordinal())));
            }
        };
        this.mChatConfigPrivate.a.setNetCallback(var1);
    }

    void setEncryptProvider(EMEncryptProvider var1) {
        this.encryptProvider = var1;
    }

    EMEncryptProvider getEncryptProvider() {
        if(this.encryptProvider == null) {
            EMLog.d("EMClient", "encrypt provider is not set, create default");
            this.encryptProvider = new EMEncryptProvider() {
                public byte[] encrypt(byte[] var1, String var2) {
                    try {
                        return EMClient.this.cryptoUtils.encrypt(var1);
                    } catch (Exception var4) {
                        var4.printStackTrace();
                        return var1;
                    }
                }

                public byte[] decrypt(byte[] var1, String var2) {
                    try {
                        return EMClient.this.cryptoUtils.decrypt(var1);
                    } catch (Exception var4) {
                        var4.printStackTrace();
                        return var1;
                    }
                }
            };
        }

        return this.encryptProvider;
    }

    boolean sendPing(boolean var1, long var2) {
        return this.emaObject.sendPing(var1, var2);
    }

    void forceReconnect() {
        this.disconnect();
        this.reconnect();
    }

    void reconnect() {
        this.wakeLock.acquire();
        this.emaObject.reconnect();
        if(this.wakeLock.isHeld()) {
            this.wakeLock.release();
        }

    }

    void disconnect() {
        this.emaObject.disconnect();
    }

    private void handleError(EMAError var1) throws HyphenateException {
        if(var1.errCode() != 0) {
            throw new HyphenateException(var1);
        }
    }

    void onNetworkChanged() {
        try {
            if(NetUtils.isWifiConnected(this.mContext)) {
                EMLog.d("EMClient", "has wifi connection");
                this.emaObject.onNetworkChanged(EMANetwork.NETWORK_WIFI);
            } else if(NetUtils.isMobileConnected(this.mContext)) {
                EMLog.d("EMClient", "has mobile connection");
                this.emaObject.onNetworkChanged(EMANetwork.NETWORK_MOBILE);
            } else if(NetUtils.isEthernetConnected(this.mContext)) {
                EMLog.d("EMClient", "has ethernet connection");
                this.emaObject.onNetworkChanged(EMANetwork.NETWORK_CABLE);
            } else {
                EMLog.d("EMClient", "no data connection");
                this.emaObject.onNetworkChanged(EMANetwork.NETWORK_NONE);
            }
        } catch (Exception var2) {
            var2.printStackTrace();
        }
    }

    void onNetworkChanged(EMANetwork var1) {
        this.emaObject.onNetworkChanged(var1);
    }

    void setAppStateListener(EMClient.AppStateListener var1) {
        this.appStateListener = var1;
    }

    @TargetApi(14)
    private void registerActivityLifecycleCallbacks() {
        if(Utils.isSdk14()) {
            ActivityLifecycleCallbacks var1 = new ActivityLifecycleCallbacks() {
                public void onActivityStopped(Activity var1) {
                    EMClient.this.activitySize--;
                    if(EMClient.this.activitySize == 0 && EMClient.this.appStateListener != null) {
                        EMClient.this.appStateListener.onBackground();
                    }

                }

                public void onActivityResumed(Activity var1) {
                    EMClient.this.activitySize++;
                    if(EMClient.this.activitySize == 1 && EMClient.this.appStateListener != null) {
                        EMClient.this.appStateListener.onForeground();
                    }

                }

                public void onActivityCreated(Activity var1, Bundle var2) {
                }

                public void onActivityStarted(Activity var1) {
                }

                public void onActivitySaveInstanceState(Activity var1, Bundle var2) {
                }

                public void onActivityPaused(Activity var1) {
                }

                public void onActivityDestroyed(Activity var1) {
                }
            };
            ((Application)this.mContext).registerActivityLifecycleCallbacks((ActivityLifecycleCallbacks)var1);
        }

    }

    void setPresence(final String var1) {
        this.execute(new Runnable() {
            public void run() {
                EMClient.this.emaObject.setPresence(var1);
            }
        });
    }

    private String getLocationString(boolean var1) {
        JSONObject var2 = null;
        if(!var1) {
            var2 = this.getDeviceInfo();
        } else {
            var2 = new JSONObject();
        }

        TelephonyManager var3 = (TelephonyManager)this.mContext.getSystemService("phone");
        String var4 = null;
        String var5 = null;
        int var6 = 0;

        try {
            String var7 = var3.getSubscriberId();
            if(var7 != null) {
                var4 = var7.substring(0, 3);
                var5 = var7.substring(3, 5);
            }

            GsmCellLocation var8 = (GsmCellLocation)var3.getCellLocation();
            if(var8 != null) {
                var6 = var8.getCid();
            }
        } catch (Exception var12) {
            EMLog.d("EMClient", var12.getMessage());
        }

        LocationManager var13 = (LocationManager)this.mContext.getSystemService("location");
        Location var14 = null;

        try {
            var14 = var13.getLastKnownLocation("network");
            if(var14 == null) {
                var14 = var13.getLastKnownLocation("gps");
            }
        } catch (Exception var11) {
            EMLog.d("EMClient", var11.getMessage());
        }

        try {
            if(var14 != null) {
                var2.put("lon", var14.getLongitude()).put("lat", var14.getLatitude());
            }

            if(var6 != 0) {
                var2.put("cellid", var6);
            }

            var2.put("wifissid", NetUtils.getWiFiSSID(this.mContext));
            if(var5 != null) {
                var2.put("mnc", var5);
            }

            if(var4 != null) {
                var2.put("mcc", var4);
            }
        } catch (JSONException var10) {
            ;
        }

        return var2.toString();
    }

    public JSONObject getDeviceInfo() {
        JSONObject var1 = new JSONObject();

        try {
            TelephonyManager var2 = (TelephonyManager)this.mContext.getSystemService("phone");
            var1.put("imei", var2.getDeviceId());
        } catch (Exception var6) {
            if(var6 != null) {
                EMLog.d("EMClient", var6.getMessage());
            }
        }

        DeviceUuidFactory var7 = new DeviceUuidFactory(this.mContext);
        String var3 = var7.getDeviceUuid().toString();

        try {
            var1.put("deviceid", var3);
            var1.put("app-id", this.mContext.getPackageName());
            var1.put("hid", getInstance().getCurrentUser());
            var1.put("os", "android");
            var1.put("os-version", VERSION.RELEASE);
            var1.put("manufacturer", Build.MANUFACTURER);
            var1.put("model", Build.MODEL);
        } catch (JSONException var5) {
            EMLog.d("EMClient", var5.getMessage());
        }

        return var1;
    }

    interface AppStateListener {
        void onForeground();

        void onBackground();
    }

    class MyMultiDeviceListener extends EMAMultiDeviceListener {
        MyMultiDeviceListener() {
        }

        public void onContactEvent(final int var1, final String var2, final String var3) {
            EMLog.d("EMClient", "onContactEvent:" + var1 + " target:" + var2 + " ext:" + var3);
            EMClient.this.execute(new Runnable() {
                public void run() {
                    synchronized(EMClient.this.multiDeviceListeners) {
                        try {
                            Iterator var2x = EMClient.this.multiDeviceListeners.iterator();

                            while(var2x.hasNext()) {
                                EMMultiDeviceListener var3x = (EMMultiDeviceListener)var2x.next();
                                var3x.onContactEvent(var1, var2, var3);
                            }
                        } catch (Exception var5) {
                            var5.printStackTrace();
                        }

                    }
                }
            });
        }

        public void onGroupEvent(final int var1, final String var2, final List<String> var3) {
            EMLog.d("EMClient", "onGroupEvent:" + var1 + " target:" + var2 + " usernames:" + var3);
            EMClient.this.execute(new Runnable() {
                public void run() {
                    synchronized(EMClient.this.multiDeviceListeners) {
                        try {
                            Iterator var2x = EMClient.this.multiDeviceListeners.iterator();

                            while(var2x.hasNext()) {
                                EMMultiDeviceListener var3x = (EMMultiDeviceListener)var2x.next();
                                var3x.onGroupEvent(var1, var2, var3);
                            }
                        } catch (Exception var5) {
                            var5.printStackTrace();
                        }

                    }
                }
            });
        }
    }

    class MyConnectionListener extends EMAConnectionListener {
        MyConnectionListener() {
        }

        public void onConnected() {
            EMClient.this.execute(new Runnable() {
                public void run() {
                    synchronized(EMClient.this.connectionListeners) {
                        try {
                            Iterator var2 = EMClient.this.connectionListeners.iterator();

                            while(var2.hasNext()) {
                                EMConnectionListener var3 = (EMConnectionListener)var2.next();
                                var3.onConnected();
                            }
                        } catch (Exception var5) {
                            var5.printStackTrace();
                        }

                    }
                }
            });
        }

        public void onDisconnected(final int var1) {
            EMClient.this.execute(new Runnable() {
                public void run() {
                    synchronized(EMClient.this.connectionListeners) {
                        if(var1 == 207) {
                            EMSessionManager.getInstance().clearLastLoginUser();
                            EMSessionManager.getInstance().clearLastLoginPwd();
                        } else if(var1 == 206 || var1 == 305 || var1 == 216 || var1 == 217) {
                            EMSessionManager.getInstance().clearLastLoginPwd();
                        }

                        try {
                            Iterator var2 = EMClient.this.connectionListeners.iterator();

                            while(var2.hasNext()) {
                                EMConnectionListener var3 = (EMConnectionListener)var2.next();
                                var3.onDisconnected(var1);
                            }
                        } catch (Exception var5) {
                            var5.printStackTrace();
                        }

                    }
                }
            });
        }
    }

    /**
     * 判断之前是否登录过
     * @return
     */
    public boolean isLoggedInBefore() {
        IMSessionManager iMSessionManager = IMSessionManager.getInstance();
        String lastLoginUser = iMSessionManager.getLastLoginUser();
        String lastLoginPwd = iMSessionManager.getLastLoginPwd();
        return lastLoginUser != null && lastLoginPwd != null && !lastLoginUser.equals("") && !lastLoginPwd.equals("");
    }

}
